<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="productName">
        <el-input
            v-model="queryParams.productName"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格型号" prop="specification">
        <el-input
            v-model="queryParams.specification"
            placeholder="请输入规格型号"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售价格" prop="price">
        <el-input
            v-model="queryParams.price"
            placeholder="请输入销售价格"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="当前库存" prop="stock">
        <el-input
            v-model="queryParams.stock"
            placeholder="请输入当前库存"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="保质期(天)" prop="shelfLife">
        <el-input
            v-model="queryParams.shelfLife"
            placeholder="请输入保质期(天)"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产地" prop="origin">
        <el-input
            v-model="queryParams.origin"
            placeholder="请输入产地"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商ID" prop="supplierId">
        <el-input
            v-model="queryParams.supplierId"
            placeholder="请输入供应商ID"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人账号ID" prop="createId">
        <el-input
            v-model="queryParams.createId"
            placeholder="请输入创建人账号ID"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable
                        v-model="queryParams.createTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新人账号ID" prop="updateId">
        <el-input
            v-model="queryParams.updateId"
            placeholder="请输入更新人账号ID"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新时间" prop="updateTime">
        <el-date-picker clearable
                        v-model="queryParams.updateTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['supermarket:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['supermarket:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['supermarket:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['supermarket:product:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品图片" align="center" width="120">
        <template slot-scope="scope">
          <el-image
              :src="scope.row.imageUrl"
              fit="cover"
              style="width: 60px; height: 60px"
              preview-src-list="[scope.row.imageUrl]">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品ID" align="center" prop="productId" />
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="销售价格" align="center" prop="price" />
      <el-table-column label="当前库存" align="center" prop="stock" />
      <el-table-column label="保质期(天)" align="center" prop="shelfLife" />
      <el-table-column label="产地" align="center" prop="origin" />
      <el-table-column label="供应商ID" align="center" prop="supplierId" />
      <el-table-column label="创建人账号ID" align="center" prop="createId" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人账号ID" align="center" prop="updateId" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['supermarket:product:edit']"
          >修改</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['supermarket:product:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="销售价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入销售价格" />
        </el-form-item>
        <el-form-item label="当前库存" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入当前库存" />
        </el-form-item>
        <el-form-item label="保质期(天)" prop="shelfLife">
          <el-input v-model="form.shelfLife" placeholder="请输入保质期(天)" />
        </el-form-item>
        <el-form-item label="产地" prop="origin">
          <el-input v-model="form.origin" placeholder="请输入产地" />
        </el-form-item>
        <el-form-item label="供应商ID" prop="supplierId">
          <el-input v-model="form.supplierId" placeholder="请输入供应商ID" />
        </el-form-item>

        <!-- 优化后的图片上传组件 -->
        <el-form-item label="商品图片">
          <el-upload
              class="upload-demo"
              action="#"
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :file-list="fileList"
              :accept="['image/jpeg', 'image/png', 'image/gif']"
              list-type="picture"
              :multiple="false"
              :limit="1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png/gif文件，且不超过2MB
            </div>
          </el-upload>
          <!-- 编辑时显示已上传图片 -->
          <el-image
              v-if="form.imageUrl && fileList.length === 0"
              :src="form.imageUrl"
              fit="cover"
              style="width: 100px; height: 100px; margin-top: 10px"
              preview-src-list="[form.imageUrl]">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </el-form-item>

        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/supermarket/product"

export default {
  name: "Product",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      productList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        specification: null,
        price: null,
        stock: null,
        shelfLife: null,
        origin: null,
        supplierId: null,
        createId: null,
        createTime: null,
        updateId: null,
        updateTime: null,
        remark: null
      },
      form: {
        imageUrl: null,
        file: null
      },
      fileList: [],
      rules: {
        productName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        specification: [
          { required: true, message: "规格型号不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "销售价格不能为空", trigger: "blur" }
        ],
        stock: [
          { required: true, message: "当前库存不能为空", trigger: "blur" }
        ],
        origin: [
          { required: true, message: "产地不能为空", trigger: "blur" }
        ],
        supplierId: [
          { required: true, message: "供应商ID不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        productId: null,
        productName: null,
        specification: null,
        price: null,
        stock: null,
        shelfLife: null,
        origin: null,
        supplierId: null,
        createBy: null,
        createId: null,
        createTime: null,
        updateBy: null,
        updateId: null,
        updateTime: null,
        status: null,
        remark: null,
        imageUrl: null,
        file: null
      }
      this.fileList = []
      this.resetForm("form")
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加商品"
    },
    handleUpdate(row) {
      this.reset()
      const productId = row.productId || this.ids
      getProduct(productId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改商品"
        // 编辑时显示已上传图片到文件列表
        if (this.form.imageUrl) {
          this.fileList = [{
            url: this.form.imageUrl,
            name: '已上传图片',
            status: 'success'
          }]
        }
      })
    },
    /** 处理文件选择 - 限制大小和数量 */
    handleFileChange(file, fileList) {
      // 限制文件大小2MB
      const maxSize = 2 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('文件大小不能超过2MB')
        this.fileList = []
        this.form.file = null
        return
      }
      // 只保留一个文件
      this.fileList = [file]
      this.form.file = file.raw
      // 选择新文件后清空原有图片地址
      this.form.imageUrl = null
    },
    /** 处理文件移除 */
    handleFileRemove() {
      this.fileList = []
      this.form.file = null
    },
    /** 提交表单 - 优化FormData构建 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const formData = new FormData()
          // 添加普通字段（过滤空值）
          Object.keys(this.form).forEach(key => {
            if (key !== 'file' && this.form[key] != null && this.form[key] !== '') {
              formData.append(key, this.form[key])
            }
          })
          // 只添加一个文件
          if (this.form.file) {
            formData.append('file', this.form.file)
          }
          // 提交请求
          if (this.form.productId != null) {
            updateProduct(formData).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            }).catch(err => {
              this.$modal.msgError("修改失败：" + (err.response?.data?.msg || '操作失败'))
            })
          } else {
            addProduct(formData).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            }).catch(err => {
              this.$modal.msgError("新增失败：" + (err.response?.data?.msg || '操作失败'))
            })
          }
        }
      })
    },
    handleDelete(row) {
      const productIds = row.productId || this.ids
      this.$modal.confirm('是否确认删除商品编号为"' + productIds + '"的数据项？').then(function() {
        return delProduct(productIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    handleExport() {
      this.download('supermarket/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
